import dayjs from "dayjs";
import conditionsDiscard from "../form/conditionsDiscard.vue";
import conditionsOutbound from "../form/conditionsOutbound.vue";
import conditionsAllocate from "../form/conditionsAllocate.vue"
import transferHighseas from "../form/transferHighseas.vue"
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { tags_list } from "@/api/tag";
import {
  customer_list,
  customer_abandoned_batch,
  customer_abandoned,
  customer_customer_insea
} from "@/api/customer";
import { addDialog } from "@/components/ReDialog";
import { type Ref, reactive, ref, onMounted, h, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type {
  conditionsDiscardItemProps,
  conditionsOutboundItemProps,
  conditionsAllocateItemProps
} from "./types";
import { deviceDetection } from "@pureadmin/utils";
import { customerData_toTask, customerData_taskDetail,distribution_original } from "@/api/outbound";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole(
  detailRef: Ref,
  redemptionRef: Ref,
  selfImportRef: Ref
) {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_cd_wl_add: false, // 补充数据
    is_cd_wl_call: false, // 添加到外呼
    is_cd_wl_tofq_condition: false, // 按条件删除到废弃
    is_cd_wl_table: false, // 物料客池列表
    is_cd_wl_dispatch: false, // 数据派发
    is_cd_wl_add_dl: false, // 兑领
    is_cd_wl_add_zd: false, // 自导入

    is_cd_wl_tofq_batch: false // 批量删除到废弃
  });

  const shortcuts = [
    {
      text: "上周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      }
    },
    {
      text: "上个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      }
    },
    {
      text: "三个月前",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      }
    }
  ];
  const labelList = ref([]);
  const intendStatusList = ref([
    {
      value: "noconnect",
      label: "未接通未确定"
    },
    {
      value: "unkown",
      label: "接通未确定"
    },
    {
      value: "refuse",
      label: "无意向"
    },
    {
      value: "intend",
      label: "有意向"
    }
  ]);
  const sourceList = ref([
    {
      value: "exchange",
      label: "兑领"
    },
    {
      value: "third",
      label: "第三方自导入"
    }
  ]);
  const form = reactive({
    type: "wuliao",
    keyword: "",
    tag_id: "",
    source_by: "",
    entry_at: "",
    called_times: "",
    page: 1,
    size: 10
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns = reactive<TableColumnList>([
    {
      type: "selection",
      align: "left"
    },
    {
      label: "企业名称",
      prop: "company_name",
      minWidth: 200
    },
    {
      label: "客户名称",
      prop: "name",
      minWidth: 100
    },
    {
      label: "联系电话",
      prop: "phone",
      minWidth: 140
    },
    {
      label: "地区",
      prop: "address_path",
      minWidth: 180
    },
    {
      label: "客户标签",
      prop: "tag_ids",
      minWidth: 140,
      formatter: ({ tag_ids }) => {
        if (!tag_ids) return "";
        let tagIds = tag_ids.split(",").map(item => item.replaceAll("_", ""));
        return tagIds
          .map(item => labelList.value.find(tag => tag.id === item)?.name)
          .join(",");
      }
    },
    {
      label: "数据来源",
      prop: "source_by",
      minWidth: 160,
      formatter: ({ source_by }) => {
        if (!source_by) return "";
        return sourceList.value.filter(item => item.value == source_by)[0]
          .label;
      }
    },
    {
      label: "被拨打次数",
      prop: "called_times",
      minWidth: 120
    },
    {
      label: "最新的意向状态",
      prop: "intend_status",
      minWidth: 180,
      formatter: ({ intend_status }) => {
        if (!intend_status) return "";
        return intendStatusList.value.filter(
          item => item.value == intend_status
        )[0].label;
      }
    },
    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 120,
      formatter: ({ created_at }) => dayjs.unix(created_at).format("YYYY-MM-DD")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ]);

  function handleCommand(e) {
    if (e == "redemption") redemptionRef.value.openDrawer();
    else selfImportRef.value.openDrawer(labelList.value);
  }

  // 按条件删除到废弃客池
  const conditionsDiscardFormRef = ref();
  function conditionsDiscardClick() {
    addDialog({
      title: "按条件删除到废弃客池",
      props: {
        formInline: {
          labelOptions: labelList.value,
          tag_ids: "",
          sourceOptions: sourceList.value,
          source: "",
          intend_status: "",
          called_times: null,
          created_at: "",
          type: 1,
          num: null
        }
      },
      width: "680px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(conditionsDiscard, {
          ref: conditionsDiscardFormRef,
          formInline: null
        }),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline as conditionsDiscardItemProps;
        function chores() {
          message(`操作成功！`, {
            type: "success"
          });
          setTimeout(() => {
            done(); // 关闭弹框
            onSearch(); // 刷新表格数据
          }, 1000);
        }
        // 客户参数选项，至少需要填写一个
        if (
          curData.tag_ids ||
          curData.source ||
          curData.intend_status ||
          curData.called_times ||
          curData.created_at.length
        ) {
          ElMessageBox.confirm("确定执行该操作？", "重要提示", {
            type: "warning"
          })
            .then(() => {
              let curForm: any = {};
              if (curData.tag_ids) curForm.tag_ids = curData.tag_ids;
              if (curData.source) curForm.source = curData.source;
              if (curData.intend_status)
                curForm.intend_status = curData.intend_status;
              if (curData.called_times)
                curForm.called_times = curData.called_times;
              if (curData.created_at.length) {
                let startTime = dayjs(curData.created_at[0]).format(
                  "YYYY-MM-DD"
                );
                let endTime = dayjs(curData.created_at[1]).format("YYYY-MM-DD");
                curForm.created_at = `${startTime},${endTime}`;
              }
              if (curData.type == 2 || curData.num) curForm.num = curData.num;
              customer_abandoned(curForm).then(res => {
                if (res.code == 1000) {
                  chores();
                } else {
                  message(res.msg, { type: "error" });
                }
              });
            })
            .catch(() => {});
        } else {
          ElMessageBox.confirm("客户参数选项，至少需要填写一个", "重要提示", {
            type: "error"
          })
            .then(() => {})
            .catch(() => {});
        }
      }
    });
  }

  // 按条件添加到外呼任务
  const conditionsOutboundFormRef = ref();
  function conditionsOutboundClick(callback?: (...args: any[]) => any) {
    addDialog({
      title: "按条件添加到外呼任务",
      props: {
        formInline: {
          labelOptions: labelList.value,
          tag_id: "",
          sourceOptions: sourceList.value,
          source: "",
          intention: [],
          called_times: "",
          entry_at: "",
          numberBy: "all",
          size: "",
          sortMode: 1,
          outboundProject: "",
          intend_status: "",
          page: "",
          sourceId: null,
          Process: null,
          showProgress: false
        }
      },
      width: "680px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(conditionsOutbound, {
          ref: conditionsOutboundFormRef,
          formInline: null
        }),
      beforeSure: (done, { options }) => {
        const FormRef = conditionsOutboundFormRef.value.getRef();
        const curData = options.props.formInline as conditionsOutboundItemProps;
        function chores() {
          message(`操作成功！`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 客户参数选项，至少需要填写一个
            if (
              curData.tag_id ||
              curData.source ||
              curData.intention.length ||
              curData.called_times ||
              curData.entry_at||
              curData.intend_status
            ) {
              ElMessageBox.confirm("确定执行该操作？", "重要提示", {
                type: "warning"
              })
                .then(() => {
                  customerData_toTask({
                    numberBy: curData.numberBy,
                    page: curData.page,
                    size: curData.size,
                    tag_id: curData.tag_id,
                    source: curData.source,
                    called_times: curData.called_times,
                    entry_at: curData.entry_at,
                    intend_status: curData.intend_status,
                    sourceId: curData.sourceId,
                    from:"wuliao"
                  }).then(res => {
                    if (res.code == 1000) {
                      localStorage.setItem('progressID', res.data.logId)
                      callback?.(res.data.logId);

                      chores();
                    }
                  });
                })
                .catch(() => {});
            } else {
              ElMessageBox.confirm(
                "客户参数选项，至少需要填写一个",
                "重要提示",
                {
                  type: "error"
                }
              )
                .then(() => {})
                .catch(() => {});
            }
          }
        });
      }
    });
  }

  // 转至公海
  function transferHighseasClick(callback?: (...args: any[]) => any) {
    addDialog({
      title: "转至公海",
      props: {
        formInline: {
          labelOptions: labelList.value,
          tag_id: "",
          sourceOptions: sourceList.value,
          source: "",
          intention: [],
          called_times: "",
          entry_at: "",
          numberBy: "all",
          size: "",
          sortMode: 1,
          outboundProject: "",
          intend_status: "",
          page: "",
          sourceId: null,
          Process: null,
          showProgress: false
        }
      },
      width: "680px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(transferHighseas, {
          ref: conditionsOutboundFormRef,
          formInline: null
        }),
      beforeSure: (done, { options }) => {
        const FormRef = conditionsOutboundFormRef.value.getRef();
        const curData = options.props.formInline as conditionsOutboundItemProps;
        function chores() {
          message(`操作成功！`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 客户参数选项，至少需要填写一个
            if (
              curData.tag_id ||
              curData.source ||
              curData.intention.length ||
              curData.called_times ||
              curData.entry_at||
              curData.intend_status
            ) {
              ElMessageBox.confirm("确定执行该操作？", "重要提示", {
                type: "warning"
              })
                .then(() => {
                  customer_customer_insea({
                    numberBy: curData.numberBy,
                    page: curData.page,
                    size: curData.size,
                    tag_id: curData.tag_id,
                    source: curData.source,
                    called_times: curData.called_times,
                    entry_at: curData.entry_at,
                    intend_status: curData.intend_status,
                    sourceId: curData.sourceId,
                  }).then(res => {
                    if (res.code == 1000) {
                      localStorage.setItem('progressID', res.data.logId)
                      callback?.(res.data.logId);

                      chores();
                    }
                  });
                })
                .catch(() => {});
            } else {
              ElMessageBox.confirm(
                "客户参数选项，至少需要填写一个",
                "重要提示",
                {
                  type: "error"
                }
              )
                .then(() => {})
                .catch(() => {});
            }
          }
        });
      }
    });
  }
  // 指定分配
    function conditionsAllocateClick(callback?: (...args: any[]) => any) {
    addDialog({
      title: "分配数据",
      props: {
        formInline: {
          labelOptions: labelList.value,
          tag_id: "",
          sourceOptions: sourceList.value,
          source: "",
          intention: [],
          called_times: "",
          entry_at: "",
          numberBy: "all",
          number: "",
          sortMode: 1,
          outboundProject: "",
          intend_status: "",
          sourceId: null,
          Process: null,
          showProgress: false,
          staffId:""
        }
      },
      width: "680px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(conditionsAllocate, {
          ref: conditionsOutboundFormRef,
          formInline: null
        }),
      beforeSure: (done, { options }) => {
        const FormRef = conditionsOutboundFormRef.value.getRef();
        const curData = options.props.formInline as conditionsAllocateItemProps;
        function chores() {
          message(`操作成功！`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            // 客户参数选项，至少需要填写一个
            if (
              curData.tag_id ||
              curData.source ||
              curData.intention.length ||
              curData.called_times ||
              curData.entry_at||
              curData.intend_status
            ) {
              ElMessageBox.confirm("确定执行该操作？", "重要提示", {
                type: "warning"
              })
                .then(() => {
                  if(curData.number <= 1000){
                    distribution_original({
                    // numberBy: curData.numberBy,
                    number: curData.number,
                    staffId: curData.staffId,
                    tag_id: curData.tag_id,
                    source: curData.source,
                    called_times: curData.called_times,
                    entry_at: curData.entry_at,
                    intend_status: curData.intend_status,
                    sourceId: curData.sourceId
                  }).then(res => {
                    if (res.code == 1000) {
                      // localStorage.setItem('progressID', res.data.logId)
                      // callback?.(res.data.logId);

                      chores();
                    }
                  });
                  }else{
                    ElMessageBox.confirm(
                "分配数量超过最大数1000，请修改！",
                "重要提示",
                {
                  type: "error"
                }
              )
                  }

                })
                .catch(() => {});
            } else {
              ElMessageBox.confirm(
                "客户参数选项，至少需要填写一个",
                "重要提示",
                {
                  type: "error"
                }
              )
                .then(() => {})
                .catch(() => {});
            }
          }
        });
      }
    });
  }

  function lookCustomer(row) {
    detailRef.value.openDrawer(row);
  }

  const tableRef = ref();
  const multipleSelection = ref([]);

  // 删除到废弃客池
  function discardClick() {
    ElMessageBox.confirm("确定执行该操作？", "重要提示", {
      type: "warning"
    })
      .then(() => {
        let curForm: any = {};
        curForm.ids_json = multipleSelection.value
          .map(item => `${item.id}:${item.table_at}:${item.version}`)
          .join(",");
        customer_abandoned_batch(curForm).then(res => {
          if (res.code == 1000) {
            message(`操作成功！`, {
              type: "success"
            });
            setTimeout(() => {
              multipleSelection.value = [];
              onSearch(); // 刷新表格数据
            }, 1000);
          } else {
            message(res.msg, { type: "error" });
          }
        });
      })
      .catch(() => {});
  }

  function handleSizeChange(val: number) {
    form.size = val;
    pagination.pageSize = val;
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val;
    onSearch(); // 刷新表格数据
  }

  function handleSelectionChange(val) {
    multipleSelection.value = val;
  }

  function handleSelectionClear() {
    const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
    clearSelection();
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    let queryFrom = { ...form };

    if (queryFrom.entry_at.length) {
      let startTime = dayjs(queryFrom.entry_at[0]).format("YYYY-MM-DD");
      let endTime = dayjs(queryFrom.entry_at[1]).format("YYYY-MM-DD");
      queryFrom.entry_at = `${startTime},${endTime}`;
    }

    const result = await customer_list(toRaw(queryFrom));

    dataList.value = result.data.list;
    pagination.total = result.data.total;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    getLabelList();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/customerManagement/data/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(
        ([key, value]) => value.onpage === "/customerManagement/data/index"
      );
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // cd_wl
      if (homeDataObj.cd_wl && homeDataObj.cd_wl.childs) {
        let permiss = homeDataObj.cd_wl.childs.join(",");
        permissions.is_cd_wl_add = permiss.includes("cd_wl_add") ? true : false;
        permissions.is_cd_wl_call = permiss.includes("cd_wl_call")
          ? true
          : false;
        permissions.is_cd_wl_tofq_condition = permiss.includes(
          "cd_wl_tofq_condition"
        )
          ? true
          : false;
        permissions.is_cd_wl_table = permiss.includes("cd_wl_table")
          ? true
          : false;
        permissions.is_cd_wl_dispatch = permiss.includes("cd_wl_dispatch")
          ? true
          : false;
        if (permiss.includes("cd_wl_table")) onSearch();
      }
      // cd_wl_add
      if (homeDataObj.cd_wl_add && homeDataObj.cd_wl_add.childs) {
        let permiss = homeDataObj.cd_wl_add.childs.join(",");
        permissions.is_cd_wl_add_dl = permiss.includes("cd_wl_add_dl")
          ? true
          : false;
        permissions.is_cd_wl_add_zd = permiss.includes("cd_wl_add_zd")
          ? true
          : false;
      }
      // cd_wl_table
      if (homeDataObj.cd_wl_table) {
        // batch
        if (
          homeDataObj.cd_wl_table.batch &&
          homeDataObj.cd_wl_table.batch.length
        ) {
          let permiss = homeDataObj.cd_wl_table.batch.join(",");
          permissions.is_cd_wl_tofq_batch = permiss.includes("cd_wl_tofq_batch")
            ? true
            : false;
        }

        let tableRemove = homeDataObj.cd_wl_table.remove
          ? homeDataObj.cd_wl_table.remove.split(",")
          : [];
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1);
            }
          }
        }
      }
    }
  });

  // 获取客户标签
  function getLabelList() {
    tags_list({
      page: 1,
      pagesize: 999,
      status: -1
    }).then(res => {
      labelList.value = res.data;
    });
  }

  let timer: any;
  const Process = ref(0); // 进度
  const showProgress = ref(false);
  // 每隔3秒查询一次任务
  function onStartQuery(task_id: any) {
    showProgress.value = true;
    timer = setInterval(() => {
      customerData_taskDetail({
        task_id
      })
        .then(res => {
          if (res.code == 1000) {
            if (res.data.status == "done") {
              Process.value = Number(res.data.process || 0) || 0;
              showProgress.value = false;
              clearInterval(timer);
            }
          }
        })
        .catch(err => {
          showProgress.value = false;
          clearInterval(timer);
        });
    }, 3000);
  }

  return {
    permissions,

    shortcuts,
    labelList,
    sourceList,
    form,
    loading,
    columns,
    dataList,
    pagination,
    tableRef,
    multipleSelection,
    Process,
    showProgress,

    handleCommand,
    conditionsOutboundClick,
    conditionsDiscardClick,
    conditionsAllocateClick,
    discardClick,
    transferHighseasClick,
    getLabelList,

    onSearch,
    resetForm,
    lookCustomer,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleSelectionClear,

    handleOffline
  };
}
